use std::fs;
use std::path::{Path, PathBuf};

fn get_video_files_recursive(
  folder_path: &str,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
  let mut video_files = Vec::new();
  let video_extensions = [
    "mp4", "avi", "mkv", "mov", "wmv", "flv", "webm", "m4v", "3gp", "mpg",
    "mpeg", "ts", "mts", "m2ts", "vob", "ogv", "ogg", "drc", "gifv", "mng",
    "avi", "mov", "qt", "wmv", "yuv", "rm", "rmvb", "asf", "amv", "m4p", "m4v",
    "svi", "3g2", "mxf", "roq", "nsv",
  ];

  // 内部递归函数
  fn visit_dirs(
    dir: &Path,
    extensions: &[&str],
    files: &mut Vec<String>,
  ) -> Result<(), Box<dyn std::error::Error>> {
    if dir.is_dir() {
      let entries = fs::read_dir(dir)?;

      for entry in entries {
        let entry = entry?;
        let path = entry.path();

        if path.is_dir() {
          // 递归访问子文件夹
          visit_dirs(&path, extensions, files)?;
        } else if path.is_file() {
          // 检查文件扩展名
          if let Some(extension) = path.extension() {
            let ext = extension.to_string_lossy().to_lowercase();
            if extensions.contains(&ext.as_str()) {
              files.push(path.to_string_lossy().to_string());
            }
          }
        }
      }
    }
    Ok(())
  }

  visit_dirs(Path::new(folder_path), &video_extensions, &mut video_files)?;
  Ok(video_files)
}

// 只返回文件名的版本
fn get_video_files_recursive_names(
  folder_path: &str,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
  let mut video_files = Vec::new();
  let video_extensions = [
    "mp4", "avi", "mkv", "mov", "wmv", "flv", "webm", "m4v", "3gp", "mpg",
    "mpeg", "ts", "mts", "m2ts", "vob", "ogv", "ogg", "drc", "gifv", "mng",
    "avi", "mov", "qt", "wmv", "yuv", "rm", "rmvb", "asf", "amv", "m4p", "m4v",
    "svi", "3g2", "mxf", "roq", "nsv",
  ];

  fn visit_dirs_names(
    dir: &Path,
    extensions: &[&str],
    files: &mut Vec<String>,
  ) -> Result<(), Box<dyn std::error::Error>> {
    if dir.is_dir() {
      let entries = fs::read_dir(dir)?;

      for entry in entries {
        let entry = entry?;
        let path = entry.path();

        if path.is_dir() {
          visit_dirs_names(&path, extensions, files)?;
        } else if path.is_file() {
          if let Some(extension) = path.extension() {
            let ext = extension.to_string_lossy().to_lowercase();
            if extensions.contains(&ext.as_str()) {
              if let Some(file_name) = path.file_name() {
                files.push(file_name.to_string_lossy().to_string());
              }
            }
          }
        }
      }
    }
    Ok(())
  }

  visit_dirs_names(
    Path::new(folder_path),
    &video_extensions,
    &mut video_files,
  )?;
  Ok(video_files)
}

// 使用 walkdir 库的更简洁版本（推荐）
// 在 Cargo.toml 中添加：walkdir = "2.3"
// fn get_video_files_walkdir(
//   folder_path: &str,
// ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
//   use walkdir::WalkDir;
//
//   let video_extensions = [
//     "mp4", "avi", "mkv", "mov", "wmv", "flv", "webm", "m4v", "3gp", "mpg",
//     "mpeg", "ts", "mts", "m2ts", "vob", "ogv", "ogg", "drc", "gifv", "mng",
//     "avi", "mov", "qt", "wmv", "yuv", "rm", "rmvb", "asf", "amv", "m4p", "m4v",
//     "svi", "3g2", "mxf", "roq", "nsv",
//   ];
//
//   let mut video_files = Vec::new();
//
//   for entry in WalkDir::new(folder_path)
//     .into_iter()
//     .filter_map(|e| e.ok())
//     .filter(|e| e.file_type().is_file())
//   {
//     if let Some(extension) = entry.path().extension() {
//       let ext = extension.to_string_lossy().to_lowercase();
//       if video_extensions.contains(&ext.as_str()) {
//         video_files.push(entry.path().to_string_lossy().to_string());
//       }
//     }
//   }
//
//   Ok(video_files)
// }

fn main() {
  let folder_path = "/home/timly/Desktop/gitworkspace/rust_stream_media_m3u8/demo3_read_file/vedios"; // 替换为你的文件夹路径

  println!("=== 递归读取完整路径 ===");
  match get_video_files_recursive(folder_path) {
    Ok(files) => {
      if files.is_empty() {
        println!("未找到视频文件");
      } else {
        println!("找到 {} 个视频文件:", files.len());
        for file in &files {
          println!("{}", file);
        }
      }
    }
    Err(e) => {
      eprintln!("读取文件夹时出错: {}", e);
    }
  }

  println!("\n=== 只返回文件名 ===");
  match get_video_files_recursive_names(folder_path) {
    Ok(files) => {
      if files.is_empty() {
        println!("未找到视频文件");
      } else {
        println!("找到 {} 个视频文件:", files.len());
        for file in &files {
          println!("{}", file);
        }
      }
    }
    Err(e) => {
      eprintln!("读取文件夹时出错: {}", e);
    }
  }

  // 如果使用 walkdir 版本，取消注释下面的代码
  /*
  println!("\n=== 使用 walkdir 库 ===");
  match get_video_files_walkdir(folder_path) {
      Ok(files) => {
          if files.is_empty() {
              println!("未找到视频文件");
          } else {
              println!("找到 {} 个视频文件:", files.len());
              for file in &files {
                  println!("{}", file);
              }
          }
      }
      Err(e) => {
          eprintln!("读取文件夹时出错: {}", e);
      }
  }
  */
}
